package com.saver.view;

import android.app.ActionBar;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.saver.R;
import com.saver.core.util.Constantes;
import com.saver.core.util.Progreso;
import com.saver.service.SMSListenerService;
import com.saver.view.adapter.NavDrawerListAdapter;
import com.saver.view.dialog.EditTransactionDialog;
import com.saver.view.dialog.RefreshActivity;
import com.saver.view.gui.FragmentSupport;
import com.saver.view.item.ConfiguracionFragment;
import com.saver.view.item.NavDrawerItem;
import com.saver.view.item.ParentViewPagerFragment;
import com.saver.view.model.FragmentModel;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends FragmentActivity implements RefreshActivity {

    private static final String TAG = "MainActivity";

    //	private GlobalState gs;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;

    NavDrawerListAdapter adapter;
    String[] navMenuTitles;
    TypedArray navMenuIcons;
    ArrayList<NavDrawerItem> navDrawerItems;
    int tipoGrafico = Constantes.TIPO_GRAFICO_PIE;
    int tipoConsulta = Constantes.CONSULTA_X_MES;

    Progreso progreso = new Progreso();

    private static RefreshActivity instance;

    private FragmentSupport currentFragment;

    public MainActivity() {
        instance = this;
    }

    public static RefreshActivity main() {
        return instance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            restoreMe(savedInstanceState);
        }
        super.onCreate(savedInstanceState);
        if (!SMSListenerService.isRunning()) {
            Intent serviceIntent = new Intent(getApplicationContext(), SMSListenerService.class);
            MainActivity.this.startService(serviceIntent);
        }
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();
        navMenuTitles = getResources().getStringArray(R.array.options_saver);
        navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        navDrawerItems = new ArrayList<NavDrawerItem>();
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (progreso != null && !progreso.isEmpty()) {
            outState.putSerializable("progreso", progreso);
            outState.putInt("tipoGrafico", tipoGrafico);
        }
    }

    private void restoreMe(Bundle state) {
        progreso = (Progreso) state.getSerializable("progreso");
        tipoGrafico = state.getInt("tipoGrafico");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        if (tipoGrafico == Constantes.TIPO_GRAFICO_NONE) {
            return true;
        }
        switch (item.getItemId()) {
//            case R.id.action_categorizar:
//                Intent intentlist = new Intent(this, ListDetailActivity.class);
//                intentlist.putExtra(Constantes.VAR_TIPO_CONSULTA, Constantes.CONSULTA_X_REVISAR);
//                startActivity(intentlist);
//                return true;
            case R.id.action_share:
                FragmentManager manager = getFragmentManager();
                EditTransactionDialog dialog = new EditTransactionDialog();
                dialog.setParent(this);
                dialog.setButtonEnabled(Dialog.BUTTON_NEGATIVE, false);
                dialog.show(manager, "Agregar movimiento");
                return true;
            case R.id.filter_anio:
                tipoConsulta = Constantes.CONSULTA_X_ANIO;
                return refresh(tipoConsulta);
            case R.id.filter_mes:
                tipoConsulta = Constantes.CONSULTA_X_MES;
                return refresh(tipoConsulta);
            case R.id.filter_dia:
                tipoConsulta = Constantes.CONSULTA_X_DIA;
                return refresh(tipoConsulta);
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private boolean refresh(int index) {
        FragmentSupport fragment = (FragmentSupport) getSupportFragmentManager().findFragmentByTag(progreso.get(progreso.size() - 1));
        fragment.getArguments().putSerializable("args", loadArguments(index));
        fragment.setTabActual(Constantes.TAB_DEFAULT);
        fragment.refresh(null);
        return true;
    }

    @Override
    public void refresh(Object params) {
        Log.d(TAG, "params: " + params);
        currentFragment.refresh((String) params); // envia la fecha
    }

    @Override
    public void reemplazarFragmento(FragmentSupport fragment) {
        if (fragment != null) {
            currentFragment = fragment;
            String currentFragment;
            if (progreso.size() == 0) {
                currentFragment = fragment.getFragmentName();
                getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, currentFragment).commit();
            } else {
                getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, fragment.getFragmentName()).addToBackStack(progreso.get(progreso.size() - 1)).commit();
                currentFragment = fragment.getFragmentName();
            }
            progreso.put(progreso.size(), currentFragment);
            if (currentFragment.equals("FRAGMENTO_RESUMEN")) {
                tipoGrafico = Constantes.TIPO_GRAFICO_PIE;
                selectedIndex(0);
            } else if (currentFragment.equals("FRAGMENTO_ESTADISTICA")) {
                tipoGrafico = Constantes.TIPO_GRAFICO_BAR;
                selectedIndex(2);
            } else if (currentFragment.equals("FRAGMENTO_REGISTRO")) {
                tipoGrafico = Constantes.TIPO_GRAFICO_LIST;
                selectedIndex(1);
            }
        } else {
            System.out.println("No se puede cambiar de fragmento");
        }
    }

    @Override
    public void selectedIndex(int position) {
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    public void selectItem(int position) {
        Log.d(TAG, "position: " + position);
        FragmentSupport fragment = null;
        Bundle bundle = new Bundle();
        switch (position) {
            case 0://RESUMEN
                tipoGrafico = Constantes.TIPO_GRAFICO_PIE;
                bundle.putSerializable("args", loadArguments(position));
                fragment = getFragmentSupport();
                fragment.setArguments(bundle);
                break;
            case 1://REGISTROS
                tipoGrafico = Constantes.TIPO_GRAFICO_LIST;
                bundle.putSerializable("args", loadArguments(position));
                fragment = getFragmentSupport();
                fragment.setArguments(bundle);
                break;
            case 2://ESTADISTICA
                tipoGrafico = Constantes.TIPO_GRAFICO_BAR;
                bundle.putSerializable("args", loadArguments(position));
                fragment = getFragmentSupport();
                fragment.setArguments(bundle);
                break;
            case 3://CONFIGURACION
                tipoGrafico = Constantes.TIPO_GRAFICO_NONE;
                fragment = new ConfiguracionFragment();
                break;
        }
        reemplazarFragmento(fragment);
        mDrawerList.setItemChecked(position, true);
        setTitle("Mingy");
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setTitle(mTitle);
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            progreso.remove(progreso.size() - 1);
            if (!progreso.isEmpty()) {
                String currentFragment = progreso.get(progreso.size() - 1);
                if (currentFragment.equals("FRAGMENTO_RESUMEN")) {
                    tipoGrafico = Constantes.TIPO_GRAFICO_PIE;
                    selectedIndex(0);
                } else if (currentFragment.equals("FRAGMENTO_ESTADISTICA")) {
                    tipoGrafico = Constantes.TIPO_GRAFICO_BAR;
                    selectedIndex(2);
                } else if (currentFragment.equals("FRAGMENTO_REGISTRO")) {
                    tipoGrafico = Constantes.TIPO_GRAFICO_LIST;
                    selectedIndex(1);
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private FragmentSupport getFragmentSupport() {
        FragmentSupport fragment = new ParentViewPagerFragment();
        switch (tipoGrafico) {
            case 2:
                fragment.setFragmentName("FRAGMENTO_RESUMEN");
                fragment.setPosition(0);
                break;
            case 1:
                fragment.setFragmentName("FRAGMENTO_ESTADISTICA");
                fragment.setPosition(1);
                break;
            case 0:
                fragment.setFragmentName("FRAGMENTO_REGISTRO");
                fragment.setPosition(2);
        }
        return fragment;
    }

    private FragmentModel loadArguments(int position) {
        FragmentModel model = new FragmentModel();
        model.setPosition(position);
        model.setTipoGrafico(tipoGrafico);
        model.setCalendar(Calendar.getInstance(new Locale("es", "pe")));
        model.setTipoConsulta(tipoConsulta);
        return model;
    }
}